﻿using BlackList.DAL;
using BlackList.Model;
using BlackList.YiYeSync;
using QWManage.DAL;
using QWManage.Excel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Threading;
using System.Web;
using System.Windows.Forms;
using RecordsDAL = BlackList.DAL.RecordsDAL;

namespace BlackList.Forms
{
    public partial class FrmYiYe : Form
    {
        private Thread _thread;
        public FrmYiYe()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (!saveConfig()) return;
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Filter = "表格文件(*.xlsx)|*.xlsx";
            if (dlg.ShowDialog() != DialogResult.OK) return;
            _thread = new Thread(new ParameterizedThreadStart(exportService));
            _thread.Start(dlg.FileName);
        }

        private HashSet<string> getExportFields()
        {
            HashSet<string> fields = new HashSet<string>();
            fields.Add("QWID"); //必要字段
            fields.Add("createdAt");//必要字段
            fields.Add("wechatAppletLandingPageViewUrl");//必要字段

            fields.Add("id");
            fields.Add("updatedAt");
            fields.Add("wechatAppletName");
            fields.Add("wechatAppletExternalUserid");
            fields.Add("wechatAppletUserid");
            fields.Add("wechatAppletGroupChatName");
            fields.Add("tagName");
            fields.Add("flowSourceName");
            return fields;
        }
        private void exportService(object obj)
        {
            try
            {
                foreach (Control control in this.Controls) control.Enabled = false;
                this.Cursor = Cursors.WaitCursor;

                string fn = (string)obj;
                RecordsDAL dal = new RecordsDAL();
                var fields = getExportFields();
                var exportTable = dal.Search(
                    fields,
                    dtpStart.Value.Date,
                    dtpEnd.Value.Date.AddDays(1).AddSeconds(-1));

                exportTable.TableName = "查询结果";
                Dictionary<string, YiYeSummaryInfo> dic = Parse(exportTable);
                DataTable summaryTable = buildSummaryTable(dic);
                ExcelHelper.DataTableToExcel(
                    new List<DataTable>() { exportTable, summaryTable }, fn);

                MessageBox.Show("导出成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (ThreadAbortException) { }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            finally
            {
                foreach (Control control in this.Controls) control.Enabled = true;
                this.Cursor = Cursors.Default;
            }
        }
        public Dictionary<string, YiYeSummaryInfo> Parse(DataTable dataTable)
        {
            YouZhaiDAL youZhaiDAL = new YouZhaiDAL();
            string name = "wechatAppletLandingPageViewUrl";
            Dictionary<string, YiYeSummaryInfo> dic = new Dictionary<string, YiYeSummaryInfo>();
            foreach (DataRow dr in dataTable.Rows)
            {
                if (dr[name] == null || dr[name] == DBNull.Value) continue;
                string url = ((string)dr[name]).Trim();
                if (string.IsNullOrEmpty(url)) continue;
                Uri uri = new Uri(url);
                var queryParameters = HttpUtility.ParseQueryString(uri.Query);
                string accountid = queryParameters["accountid"];
                string aid = queryParameters["aid"];
                string cid = queryParameters["cid"];
                string key = accountid + "_" + aid + "_" + cid;

                if (string.IsNullOrEmpty(accountid) && string.IsNullOrEmpty(aid) && string.IsNullOrEmpty(cid))
                    continue;

                if (!dic.ContainsKey(key))
                {
                    dic.Add(key, new YiYeSummaryInfo()
                    {
                        aid = aid,
                        cid = cid,
                        accountid = accountid,
                        YiYe = 0,
                        Valid = 0,
                        DY = 0,
                        DY_P = 0,
                        JD = 0,
                        JD_P = 0,
                        PDD = 0,
                        PDD_P = 0,
                        TB = 0,
                        TB_P = 0,
                        Total = 0,
                        Average = 0
                    });
                }
                YiYeSummaryInfo summary = dic[key];
                summary.YiYe += 1;
                if (dr["QWID"] == null || dr["QWID"] == DBNull.Value) continue;
                string qwid = (string)dr["QWID"];
                var youzhai = youZhaiDAL.GetYouZhaiInfo(qwid);
                if (youzhai != null)
                {
                    summary.Valid += 1;
                    summary.DY += youzhai.dy.HasValue ? youzhai.dy.Value : 0;
                    summary.DY_P = (decimal)summary.DY / summary.Valid * 100;

                    summary.PDD += youzhai.pdd.HasValue ? youzhai.pdd.Value : 0;
                    summary.PDD_P = (decimal)summary.PDD / summary.Valid * 100;

                    summary.TB += youzhai.tb.HasValue ? youzhai.tb.Value : 0;
                    summary.TB_P = (decimal)summary.TB / summary.Valid * 100;

                    summary.JD += youzhai.jd.HasValue ? youzhai.jd.Value : 0;
                    summary.JD_P = (decimal)summary.JD / summary.Valid * 100;

                    summary.Total += youzhai.yongjin.HasValue ? youzhai.yongjin.Value : 0;
                    summary.Average = summary.Total / summary.YiYe * 100;
                }
            }
            return dic;
        }
        private DataTable buildSummaryTable(Dictionary<string, YiYeSummaryInfo> dic)
        {
            DataTable dataTable = new DataTable();
            dataTable.TableName = "汇总";
            dataTable.Columns.Add(new DataColumn() { ColumnName = "accountid" });
            dataTable.Columns.Add(new DataColumn() { ColumnName = "aid" });
            dataTable.Columns.Add(new DataColumn() { ColumnName = "cid" });

            dataTable.Columns.Add(new DataColumn() { ColumnName = "一叶人数" });
            dataTable.Columns.Add(new DataColumn() { ColumnName = "有效人数" });

            dataTable.Columns.Add(new DataColumn() { ColumnName = "抖音人数" });
            dataTable.Columns.Add(new DataColumn() { ColumnName = "抖音比例" });

            dataTable.Columns.Add(new DataColumn() { ColumnName = "淘宝人数" });
            dataTable.Columns.Add(new DataColumn() { ColumnName = "淘宝比例" });

            dataTable.Columns.Add(new DataColumn() { ColumnName = "京东人数" });
            dataTable.Columns.Add(new DataColumn() { ColumnName = "京东比例" });

            dataTable.Columns.Add(new DataColumn() { ColumnName = "拼多多人数" });
            dataTable.Columns.Add(new DataColumn() { ColumnName = "拼多多比例" });

            dataTable.Columns.Add(new DataColumn() { ColumnName = "平均佣金" });

            foreach (YiYeSummaryInfo summaryInfo in dic.Values)
            {
                DataRow dr = dataTable.NewRow();
                dr["accountid"] = summaryInfo.accountid;
                dr["aid"] = summaryInfo.aid;
                dr["cid"] = summaryInfo.cid;
                dr["一叶人数"] = summaryInfo.YiYe;
                dr["有效人数"] = summaryInfo.Valid;

                dr["抖音人数"] = summaryInfo.DY;
                dr["抖音比例"] = summaryInfo.DY_P.ToString("0.00") + "%";

                dr["淘宝人数"] = summaryInfo.TB;
                dr["淘宝比例"] = summaryInfo.TB_P.ToString("0.00") + "%";

                dr["京东人数"] = summaryInfo.JD;
                dr["京东比例"] = summaryInfo.JD_P.ToString("0.00") + "%";


                dr["拼多多人数"] = summaryInfo.PDD;
                dr["拼多多比例"] = summaryInfo.PDD_P.ToString("0.00") + "%";

                dr["平均佣金"] = summaryInfo.Average.ToString("0.00");
                dataTable.Rows.Add(dr);
            }
            return dataTable;
        }
        private void FrmYiYe_Load(object sender, EventArgs e)
        {
            var config = YiYeSearchConfigMgr.Get();
            dtpStart.Value = config.Start;
            dtpEnd.Value = config.End;

            Control.CheckForIllegalCrossThreadCalls = false;
            this.FormClosing += (ss, ee) =>
            {
                if (_thread != null && _thread.IsAlive) _thread.Abort();
            };
        }
        private bool saveConfig()
        {
            if (dtpEnd.Value.Date < dtpStart.Value.Date)
            {
                MessageBox.Show(
                    "结束日期不能小于开始日期",
                    "提示",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Warning);
                return false;
            }

            YiYeSearchConfigInfo config = new YiYeSearchConfigInfo();
            config.Start = dtpStart.Value;
            config.End = dtpEnd.Value;
            YiYeSearchConfigMgr.Set(config);
            return true;
        }

        private void yiyeMatchQWService()
        {
            try
            {
                foreach (Control control in this.Controls) control.Enabled = false;
                this.Cursor = Cursors.WaitCursor;
                YiYeSyncMgr.Execute();
                MessageBox.Show("匹配完成", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
            catch (ThreadAbortException) { }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            finally
            {
                foreach (Control control in this.Controls) control.Enabled = true;
                this.Cursor = Cursors.Default;
            }
        }
        private void btnYiYeMatchQW_Click(object sender, EventArgs e)
        {
            _thread = new Thread(new ThreadStart(yiyeMatchQWService));
            _thread.Start();
        }
        private void QWMatchYouZhaiService()
        {
            try
            {
                foreach (Control control in this.Controls) control.Enabled = false;
                this.Cursor = Cursors.WaitCursor;
                CustomerDAL customerDAL = new CustomerDAL();
                var dic = customerDAL.GetAvatarDic();

                YouZhaiDAL youZhaiDAL = new YouZhaiDAL();
                var youzhais = youZhaiDAL.GetYouZhaiInfos();
                foreach (var youzhai in youzhais)
                {
                    string avatar = youzhai.headImg;
                    if (string.IsNullOrEmpty(avatar)) continue;
                    if (dic.ContainsKey(avatar))
                    {
                        youZhaiDAL.UpdateQWID(youzhai.id, dic[avatar]);
                    }
                }
                MessageBox.Show("匹配完成", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (ThreadAbortException) { }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            finally
            {
                foreach (Control control in this.Controls) control.Enabled = true;
                this.Cursor = Cursors.Default;
            }
        }
        private void btnQWMatchYouZhai_Click(object sender, EventArgs e)
        {
            _thread = new Thread(new ThreadStart(QWMatchYouZhaiService));
            _thread.Start();
        }
    }
}
